<template>
  <view class="container">
    <uni-forms
      ref="formRef"
      :model="formData"
      :rules="rules"
      label-position="top"
      label-width="75vw"
      class="form">
      <uni-forms-item name="isTransportCode" required label="有无交委电子运单">
        <uni-data-checkbox
          v-model="formData.isTransportCode"
          :localdata="optionItems">
        </uni-data-checkbox>
      </uni-forms-item>
      <uni-forms-item name="transportCode" label="电子运单" v-if="formData.isTransportCode == 1" required>
        <uni-easyinput suffixIcon="scan" type="text" @change="onChangeTransportCode" v-model="formData.transportCode" placeholder="请输入或扫描电子运单" maxlength="24" @iconClick="onClickScanCode" />
      </uni-forms-item>
      <div style="display: flex;">
        <div style="margin-right: 8px;width:49%;">
          <uni-forms-item name="carNo" required label="承运车辆车牌号">
            <uni-easyinput type="text" v-model="formData.carNo" placeholder="请输入车牌号" />
          </uni-forms-item>
        </div>

        <div style="width:49%;">
          <uni-forms-item name="containerNumber" label="">
            <uni-easyinput type="text" v-model="formData.containerNumber" placeholder="请输入挂车车牌号" />
          </uni-forms-item>
        </div>
      </div>

      <uni-forms-item name="tankCode" label="槽罐编号">
        <uni-easyinput type="text" v-model="formData.tankCode" placeholder="请输入槽罐编号" />
      </uni-forms-item>

      <uni-forms-item name="inoutPurpose" label="出入目的" required>
        <uni-data-checkbox
          v-model="formData.inoutPurpose"
          :localdata="optionItemsMd">
        </uni-data-checkbox>
      </uni-forms-item>

      <uni-forms-item name="isToOuter" label="是否发往外省市" required>
        <uni-data-checkbox
          v-model="formData.isToOuter"
          :localdata="optionItemsIsToOuter">
        </uni-data-checkbox>
      </uni-forms-item>

      <view class="item">
        <view class="red">（如无法在预计时间前装卸，请重新上报）</view>
        <uni-forms-item name="planDate" label="预计时间" required>
          <uni-datetime-picker
            v-model="formData.planDate"
            placeholder="请选择预计时间"
            type="datetime"
            :hide-second="true"
            @change="changeTime">
          </uni-datetime-picker>
        </uni-forms-item>
      </view>

      <view class="item">
        <view class="red red2">（请填写企业全称）</view>
        <uni-forms-item name="belongEnterprise" label="承运企业名称" required>
          <uni-easyinput type="text" v-model="formData.belongEnterprise" placeholder="请输入承运企业名称" />
        </uni-forms-item>
      </view>
      
      <uni-forms-item name="carType" label="车辆性质" required>
        <uni-data-select
          v-model="formData.carType"
          :localdata="carTypeList"
          :clear="false"
          placeholder="请选择车辆性质"
          ></uni-data-select>
      </uni-forms-item>
      
      <!-- <uni-forms-item name="containerNumber" label="挂车车牌号" required>
        <uni-easyinput type="text" v-model="formData.containerNumber" placeholder="请输入" />
      </uni-forms-item> -->

      <uni-forms-item name="driverName" label="承运车辆驾驶员姓名" required>
        <uni-easyinput type="text" maxlength="20" v-model="formData.driverName" placeholder="请输入承运车辆驾驶员姓名" />
      </uni-forms-item>

      <uni-forms-item name="driverIdcard" label="承运车辆驾驶员身份证号" required>
        <uni-easyinput type="text" maxlength="18" v-model="formData.driverIdcard" placeholder="请输入承运车辆驾驶员身份证号" />
      </uni-forms-item>
      <uni-forms-item name="escort" label="押运员姓名" required>
        <uni-easyinput type="text" maxlength="20" v-model="formData.escort" placeholder="请输入押运员姓名" />
      </uni-forms-item>
      <uni-forms-item name="escortIdcard" label="押运员身份证号" required>
        <uni-easyinput type="text" maxlength="18" v-model="formData.escortIdcard" placeholder="请输入押运员身份证号" />
      </uni-forms-item>

      <view class="item">
        <view class="red red3">（请填写企业全称，如无企业名称则不填）</view>
        <uni-forms-item name="receiveEnterpriseName" label="收货企业名称">
          <!-- <uni-data-select
            v-model="receiveEnterpriseName"
            :localdata="enterpriseList"
            :clear="false"
            ></uni-data-select> -->
          
          <uni-easyinput type="text" v-model="formData.receiveEnterpriseName" @change="onChange" placeholder="请输入收货企业名称" />
          <!-- @input="onInputChange" @focus="searchPicker=true"  -->

          <!-- <div class="agentSeach" v-if="searchPicker">
            <div class="closeIcon">选择收货企业名称
              <span class="close" @click="closeSearch">关闭</span>
            </div>
            <div class="generate-formWork"
                :class="{ 'generate-selected' : index == selIndex }"
                v-for="(item,index) in searchList"
                :key="item.id"
                @click="selectName(item.id,item.text)">
              <span>{{item.text}}</span>
            </div>
            <div v-if="searchList.length == 0 && formData.receiveEnterpriseName !== ''" class="noOptions">
              暂无匹配选项
            </div>
          </div> -->
        </uni-forms-item>
        
        <!-- <uni-forms-item name="receiveEnterpriseNo">
          <view class="title">收货企业信用代码</view>
          <uni-easyinput type="text" v-model="formData.receiveEnterpriseNo" placeholder="请输入" />
        </uni-forms-item> -->
      </view>
      <!-- <uni-forms-item name="receiveEnterpriseId" required>
        <view class="title">发货后接收企业ID</view>
        <uni-easyinput type="text" v-model="formData.receiveEnterpriseId" placeholder="请输入" />
      </uni-forms-item> -->
    </uni-forms>
    
    <div class="ft">
      <button type="primary" @click="handleSubmit">提交</button>
    </div>
  </view>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { apis as APIS } from "@/api/yiqiyipin.js";
import { router } from "@/router/index.js";

const formData = ref({
  carNo: '',
  tankCode: '',
  transportCode: '',
  inoutPurpose: '',  
  isTransportCode: 1
});

const selIndex = ref(null)
const searchList = ref([])
const searchPicker = ref(false)

const rules = ref({
  isTransportCode: {
    rules: [{ required: true, errorMessage: "请选择有无交委电子运单" }],
  },
  transportCode: {
    rules: [{ required: true, errorMessage: "请扫描或输入电子运单" },
    {
      validateFunction: function(rule,value,data,callback){
        let reg = /^([\dA-Za-z]){24}$/
        if(!reg.test(value)) {
          callback('请输入正确的电子运单')
        }
        return true
      }
    }],
  },
  carNo: {
    rules: [
      { required: true, errorMessage: "请输入承运车辆车牌号" },
      {
        validateFunction: function(rule,value,data,callback){
          let reg = /^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼港澳]{1}[A-Za-z]{1}[A-HJ-NP-Z0-9]{5}$|^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[D|F]{1}[A-HJ-NP-Z0-9]{5}$|^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[A-Z]{1}[0-9]{6}$|^WJ[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[0-9]{5}$|^使[0-9]{3}[A-Z]{1}$|^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[A-Z]{1}挂[0-9]{4}$|^[京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽贵青藏川宁琼]{1}[A-Z]{1}警[0-9]{4}$|^粤Z[A-HJ-NP-Z0-9]{4,5}(港|澳)?$/
          if(!reg.test(value)) {
            callback('请输入正确的承运车辆车牌号')
          }
          return true
        }
      }
    ],
  },
  inoutPurpose: {
    rules: [{ required: true, errorMessage: "请选择出入目的" }]
  },
  isToOuter: {
    rules: [{ required: true, errorMessage: "请选择是否发往外省市" }]
  },
  planDate: {
    rules: [{ required: true, errorMessage: "请选择预计时间" }]
  },
  belongEnterprise: {
    rules: [{ required: true, errorMessage: "请输入承运企业名称" }]
  },
  carType: {
    rules: [{ required: true, errorMessage: "请选择车辆性质" }]
  },
  // containerNumber: {
  //   rules: [{ required: true, errorMessage: "请选输入挂车车牌号" }]
  // },
  driverName: {
    rules: [{ required: true, errorMessage: "请输入承运车辆驾驶员姓名" }]
  },
  driverIdcard: {
    rules: [{ required: true, errorMessage: "请输入承运车辆驾驶员身份证号" },
    {
      validateFunction: function(rule,value,data,callback){
        let reg = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/
        if(!reg.test(value)) {
          callback('请输入正确的身份证号格式')
        }
        return true
      }
    }]
  },
  escort: {
    rules: [{ required: true, errorMessage: "请输入押运员姓名" }]
  },
  escortIdcard: {
    rules: [{ required: true, errorMessage: "请输入押运员身份证号" },
    {
      validateFunction: function(rule,value,data,callback){
        let reg = /^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/
        if(!reg.test(value)) {
          callback('请输入正确的身份证号格式')
        }
        return true
      }
    }]
  }
});

const optionItems = [
  {
    value: 1,
    text: "有交委电子运单",
  },
  {
    value: 2,
    text: "无交委电子运单",
  }
]

const optionItemsMd = [
  {
    value: 1,
    text: "装车发货",
  },
  {
    value: 2,
    text: "收货入库",
  }
]

const optionItemsIsToOuter = [
  {
    value: 1,
    text: "是",
  },
  {
    value: 0,
    text: "否",
  }
]

// 企业
const enterpriseList = ref([])
const fGetEnterpriseList = (e) => {
  APIS.enterpriseList().then((res) => {
    if(res.code === 200){
      res.data.map(item => {
        enterpriseList.value.push({
          id: item.id,
          value: item,
          text: item.enterpriseName
        })
      })
      searchList.value = enterpriseList.value
    }
  });
}
fGetEnterpriseList()

// 车辆性质字典接口404
const carTypeList = ref([{
  value: 1,
  text: '集装箱车'
},
{
  value: 2,
  text: '槽罐车'
},
{
  value: 3,
  text: '普通危险化学品车'
},
{
  value: 5,
  text: '管道'
},
{
  value: 6,
  text: '挂车'
},
{
  value: 7,
  text: '槽罐挂车'
},
{
  value: 8,
  text: '集装箱挂车'
},
{
  value: 0,
  text: '非危险化学品车'
}])
// const fGetCarType = (e) => {
//   APIS.getCarType().then((res) => {
//     if(res.code === 200){
//       res.data.map(item => {
//         carTypeList.value.push({
//           value: item,
//           text: item
//         })
//       })
//     }
//   });
// }
// fGetCarType()

const carList = ref([])

// 输入电子运单号
const onChangeTransportCode = (e) => {
  if(e){
    APIS.carNumList({  transportCode: formData.value.transportCode  }).then((res) => {
      if(res.code === 200){
        formData.value = {
          ...formData.value,
          ...res.data
        }
      }
    });
  }
}

const onClickScanCode = (e) => {
  console.log('扫一扫')
  // 扫码出来的内容，车牌号传给接口
  // let str = '02$01$310002032324082200216865$沪FF**63,黄色$王磊,320826******143430,陈太露,321323******243337$mAp4VAYDZKA/j5uMBioanmG4RTBnZbluq+wZmDeGm8iS85i2F70J6JVMy57BeJa4dHW2cbFnrreUDr3U9nFLkA=='

  // formData.value.transportCode = str.split('$')[2]
  // let carNo = str.split('$')[3].split(',')[0]

  // 根据加密车牌，查询匹配车牌号  -- 旧接口 废弃
  // APIS.carNumList({ carNo }).then((res) => {
  //   if(res.code === 200){
  //     res.data.carList.map(item => {
  //       carList.value.push({
  //         value: item.carNo,
  //         text: item.carNo
  //       })
  //     })
  //   }
  // });

  // 新接口传参
  // APIS.carNumList({ transportCode: formData.value.transportCode }).then((res) => {
  //   if(res.code === 200){
  //     formData.value = res.data
  //     // res.data.carList.map(item => {
  //     //   carList.value.push({
  //     //     value: item.carNo,
  //     //     text: item.carNo
  //     //   })
  //     // })
  //   }
  // });

  uni.scanCode({
    onlyFromCamera: false, // 是否只从相机扫码，不从相册选择图片
    scanType: ['qrCode'], // 扫描的类型
    success: function (res) {
      console.log('扫描结果：', res.result);
      console.log('扫描条码类型：', res.scanType);
      // console.log('字符集：', res.charSet);
      // console.log('路径：', res.path); // 当所扫的码为小程序码时会返回此项

      if(res.result){
        formData.value.transportCode = res.result.split('$')[2]
        let carNo = res.result.split('$')[3].split(',')[0]

        // 根据加密车牌，查询匹配车牌号
        APIS.carNumList({  transportCode: formData.value.transportCode  }).then((res) => {
          if(res.code === 200){
            formData.value = res.data
          }
        });
      }
    },
    fail: function (err) {
      console.error('扫码失败：', err);
    },
    complete: function () {
      console.log('扫码操作完成');
    }
  });
}


const formRef = ref();
const receiveEnterpriseName = ref({})
const handleSubmit = (data) => {
  console.log('formData.value.carType', formData.value.carType)
  console.log('formData.value.tankCode', formData.value.tankCode)

  formRef.value.validate().then((res) => {
    let data = {
      ...formData.value,
      // receiveEnterpriseName: receiveEnterpriseName.value.enterpriseName,
      // receiveEnterpriseId: receiveEnterpriseName.value.id
    }

    if(formData.value.carType == 7 && (formData.value.tankCode == '' || formData.value.tankCode == null)){
      return uni.showToast({
        title: '请填写槽罐编号！',
        icon: 'none',
        duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
        mask:false, // 是否显示透明蒙层，防止触摸穿透，默认：false
      })
    }

    APIS.carSign(data).then((res) => {
      if(res.code === 200){
        uni.showToast({
          title: '提交成功！',
          icon: 'success',
          duration: 2000, //提示的延迟时间，单位毫秒，默认：1500
          mask:false, // 是否显示透明蒙层，防止触摸穿透，默认：false
        });
        setTimeout(() => {
          router.toPage({
            path: "/pages/home/index"
          });
        }, 2000);
      }
    });
  })
  .catch((err) => {
    console.log("表单错误信息", err);
  });
}

const onChange = () => {
  formData.value.receiveEnterpriseId = 0
}

const onInputChange = (val) => { // 监听输入框的变化实现模糊查询
  formData.value.receiveEnterpriseName = val
  // searchPicker.value = true
  if (formData.value.receiveEnterpriseName === '' || formData.value.receiveEnterpriseName === null || formData.value.receiveEnterpriseName === undefined || selIndex.value!== null) { // 去除勾选状态
    selIndex.value =null
  }

  console.log('enterpriseList.value', enterpriseList.value)

  searchList.value = enterpriseList.value.filter(i => {
    console.log('i==', i)
    console.log('val==', val)
    return i.id.includes(val) || i.text.includes(val)
  })

  console.log('searchList.value', searchList.value)
}

const closeSearch = () => { // 关闭模糊查询
  searchPicker.value = false
  formData.value.receiveEnterpriseId = 0
}

const selectName = (id,name) => { // 赋值选中状态
  searchList.value.forEach( (item,index) => {
    console.log('item:', item)
    if (item.id === id && item.text === name) {

      console.log('name:', name)
      console.log('id:', id)

      selIndex.value = index
      formData.value.receiveEnterpriseName = name
      formData.value.receiveEnterpriseId = id
      searchPicker.value = false

      console.log('formData.value', formData.value)
    }
  })
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20upx;
  background: #fff;

  .title{
    // font-weight: 500;
    font-size: 28upx;
    padding-bottom: 10upx;
  }

  .ft{
    width: 100%;
    // position: fixed;
    // left: 0;
    // bottom: 0;
    // z-index: 99999;
  }
}

.posDiv{
  position: relative;
  z-index: 999;
  .closeIcon{
    display: flex;
    justify-content: center;
    line-height: 40px;
    font-size: 12px;
    .close{
      position: absolute !important;
      top: 0;
      right: 10px;
    }
  }
  .agentSeach{
    width: 100%;
    position: absolute;
    right: 1%;
    background: #fff;
    box-shadow: 0 0px 5px #e3dddd;
    .noOptions{
      text-align: center;
      color: red;
      line-height: 48px;
    }
  }
  .generate-formWork{
    color: #666;
    display: flex;
    align-items: center;
    font-size: 14px;
    margin: 0 24px;
    height: 28px;
    word-break: break-all;
  }
  .generate-selected{
    color: #494DF4;
    // background-image: url("../static/img/checked.png");
    background-repeat: no-repeat;
    background-size: 18px;
    background-position: right;
  }
}

.item{
  position: relative;
  .red{
    color: #c00;
    position: absolute;
    top: 10upx;
    left: 130upx;
    z-index: 8;
    font-size: 20upx;
  }
  .red2{
    left: 180upx;
  }
  .red3{
    left: 170upx;
  }
}
</style>
